package cn.lili.modules.system.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.cache.util.RedisUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.modules.system.entity.dos.Dictionary;
import cn.lili.modules.system.entity.params.DictionarySearchParams;
import cn.lili.modules.system.mapper.DictionaryMapper;
import cn.lili.modules.system.service.DictionaryService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangfei
 * @description 针对表【dictionry】的数据库操作Service实现
 * @createDate 2023-07-27 15:28:03
 */

@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary>
        implements DictionaryService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<Dictionary> dictionryList(String code, String value) {
        LambdaQueryWrapper<Dictionary> dictionryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(code)) {
            dictionryLambdaQueryWrapper.eq(Dictionary::getCode, code);
        }
        if (StringUtils.isNotEmpty(value)) {
            dictionryLambdaQueryWrapper.eq(Dictionary::getValue, value);
        }
        dictionryLambdaQueryWrapper.eq(Dictionary::getStatus, DictConstant.STATUS_1);
        return super.list(dictionryLambdaQueryWrapper);
    }

    @Override
    public List<Dictionary> dictionryListByCode(String code, Integer value) {
        try {
//            List<Dictionary> obj = redisUtil.get(code, ArrayList.class);
//            if (CollectionUtil.isNotEmpty(obj)) {
//                return obj;
//            }
            LambdaQueryWrapper<Dictionary> dictionryLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotEmpty(code)) {
                dictionryLambdaQueryWrapper.eq(Dictionary::getCode, code);
            }
            if (value != null) {
                dictionryLambdaQueryWrapper.eq(Dictionary::getValue, value);
            }
            dictionryLambdaQueryWrapper.eq(Dictionary::getStatus, DictConstant.STATUS_1);
            List<Dictionary> list = super.list(dictionryLambdaQueryWrapper);
            redisUtil.set(code, list, 60 * 60 * 24);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<Dictionary> dictionryListByCodeList(List<String> codes) {
        LambdaQueryWrapper<Dictionary> dictionryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtils.isNotEmpty(codes)) {
            dictionryLambdaQueryWrapper.in(Dictionary::getCode, codes);
        }
        dictionryLambdaQueryWrapper.eq(Dictionary::getStatus, DictConstant.STATUS_1);
        return super.list(dictionryLambdaQueryWrapper);
    }

    @Override
    public ResultMessage<Object> pageVo(DictionarySearchParams params) {
        LambdaQueryWrapper<Dictionary> dictionaryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (params.getStatus() != null) {
            dictionaryLambdaQueryWrapper.eq(Dictionary::getStatus, params.getStatus());
        }
        if (StringUtils.isNotEmpty(params.getId())) {
            dictionaryLambdaQueryWrapper.eq(Dictionary::getId, params.getId());
        }
        if (StringUtils.isNotEmpty(params.getCode())) {
            //不可以like ，前端有地方使用。部分一样会导致匹配上多个字典
            dictionaryLambdaQueryWrapper.eq(Dictionary::getCode, params.getCode());
        }
        if (StringUtils.isNotEmpty(params.getValue())) {
            dictionaryLambdaQueryWrapper.like(Dictionary::getValue, params.getValue());
        }
        if (StringUtils.isNotEmpty(params.getValueName())) {
            dictionaryLambdaQueryWrapper.like(Dictionary::getValueName, params.getValueName());
        }
        if (StringUtils.isNotEmpty(params.getDescription())) {
            dictionaryLambdaQueryWrapper.like(Dictionary::getDescription, params.getDescription());
        }
        dictionaryLambdaQueryWrapper.orderByDesc(Dictionary::getCreateTime);
        return ResultUtil.data(super.page(PageUtil.initPage(params), dictionaryLambdaQueryWrapper));
    }

    /**
     * 校验数据，防止重复
     */
    @Override
    public void check(Dictionary dictionary) {
        LambdaQueryWrapper<Dictionary> dictionaryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictionaryLambdaQueryWrapper.eq(Dictionary::getStatus, DictConstant.STATUS_1);
        dictionaryLambdaQueryWrapper.eq(Dictionary::getCode, dictionary.getCode());
        dictionaryLambdaQueryWrapper.eq(Dictionary::getValue, dictionary.getValue());
        if (StringUtils.isNotEmpty(dictionary.getId())) {
            dictionaryLambdaQueryWrapper.ne(Dictionary::getId, dictionary.getId());
        }
        if (super.count(dictionaryLambdaQueryWrapper) > 0) {
            throw new ServiceException("字典值已存在：字典=" + dictionary.getCode() + ", 值=" + dictionary.getValue());
        }
        //清除缓存
        this.clearCache(dictionary.getCode());
    }

    /**
     * 清除缓存
     * @param code code码
     */
    private void clearCache(String code) {
        LambdaQueryWrapper<Dictionary> dictionaryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictionaryLambdaQueryWrapper.eq(Dictionary::getCode, code);
        List<Dictionary> dictionaryList = super.list(dictionaryLambdaQueryWrapper);
        for (Dictionary dict : dictionaryList) {
            redisUtil.removeKey(dict.getCode());
        }
    }

    /**
     * 状态变更
     */
    @Override
    public Boolean change(String id, Integer status) {
        Dictionary dictionary = super.getById(id);
        if (dictionary == null) {
            return false;
        }
        this.clearCache(dictionary.getCode());
        dictionary.setStatus(status);
        return super.updateById(dictionary);
    }

    @Override
    public Boolean getActivityPop () {
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getCode, "activity_pop");
        queryWrapper.last("limit 1");
        Dictionary dictionary = this.getOne(queryWrapper);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != dictionary) {
            String[] dates = dictionary.getValueName().split("至");
            try {
                Date startTime = sdf.parse(dates[0]);
                Date endTime = sdf.parse(dates[1]);
                if (new Date().after(startTime) && new Date().before(endTime)) {
                    return true;
                }
            }catch (Exception e) {
                log.error("日期转换异常");
            }
        }
        return false;
    }
}




